package com.wunu.smartlock1.activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.wunu.smartlock1.R;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockTempKeyApi;
import com.wunu.smartlock1.net.response.ApiData;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.ApiSimpleResponse;
import com.wunu.smartlock1.net.response.TempKeyDetail;
import com.wunu.smartlock1.util.CommonUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;

/**
 * Created by admin on 2018/4/21.
 */

public class TemporyLockShowActivity extends AppCompatActivity{
    TextView temporaryKeyTextView;//临时密码
    TextView temporaryNameTextView;//名称
    TextView dateTextView;//生效时间
    TextView timeTextView;//生效时间
    TextView validTimeValueTextView;//有效时长
    TextView validTermsTextView;//有效次数

    Button button;
    long tempKeyId;
    String toast;
    int state;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            System.out.println("msg----------------------->:"+msg);
            System.out.println("obj->"+msg.getData());
            switch (msg.what){
                case 0:
                    break;
                case 2:
                    ApiNormalResponse<TempKeyDetail> resp = (ApiNormalResponse<TempKeyDetail>)msg.obj;
                    if(resp == null || resp.getCode()!=0 || resp.getData().getCode() != 200){
                        Toast.makeText(TemporyLockShowActivity.this, "获取临时密钥详细信息失败!", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    TempKeyDetail td = resp.getData().getData();
                    temporaryNameTextView.setText("名称:" + td.getLockName());
                    temporaryKeyTextView.setText(String.valueOf(td.getTempKey()));

                    validTimeValueTextView.setText(String.format("%.2f",td.getValidTime()/60/60)+"小时");
                    validTermsTextView.setText(String.valueOf(td.getValidCount())+"次");
                    dateTextView.setText(td.getStartTime().substring(0,10));
                    timeTextView.setText(td.getStartTime().substring(11,16));

                    state = td.getState();
                    toast = state == 0?"领取":"确认";
                    button.setText(toast);
                    break;
                case 3:
                    if(state == 0){
                        ApiSimpleResponse rsp = (ApiSimpleResponse) msg.obj;
                    }else {
                        ApiNormalResponse<TempKeyDetail> as = (ApiNormalResponse<TempKeyDetail>) msg.obj;
                    }
                    break;
            }

        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smartlock_lock_temporylock);
        //生效时间
        dateTextView = findViewById(R.id.dateTextView);
        timeTextView = findViewById(R.id.timeTextView);
        validTimeValueTextView = findViewById(R.id.validTimeValueTextView);
        validTermsTextView = findViewById(R.id.validTermsTextView);

        temporaryKeyTextView = findViewById(R.id.temporaryKeyTextView);
        temporaryNameTextView = findViewById(R.id.temporaryNameTextView);

        button = findViewById(R.id.sendSMS);
        button.setText("领取");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(TemporyLockShowActivity.this, toast+"临时密钥!", Toast.LENGTH_SHORT).show();
                new Thread(){
                    @Override
                    public void run(){
                        //发送请求获取临时密钥详细信息
                        LockTempKeyApi service = NetComponent.getRetrofit().create(LockTempKeyApi.class);
                        System.out.println("tempKeyId: "+tempKeyId);
                        try {
                            Object obj = null;
                            Call<ApiNormalResponse<TempKeyDetail>> call = service.tempKeyDetail(tempKeyId);
                            System.out.println("state: "+state);
                            if(state == 0) {
                                obj = service.confirmTempKey(tempKeyId).execute().body();
                            }else{
                                obj = service.tempKeyDetail(tempKeyId).execute().body();
                            }
                            System.out.println("临时密钥详情： "+obj);
                            // 判断锁是否绑定成功
                            Message msg = handler.obtainMessage();
                            msg.obj = obj;
                            msg.what = 3;
                            handler.sendMessage(msg);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        //左上角箭头返回主界面时，不要再判断剪切板内容了
        CommonUtil.dump = false;
        //begin 添加获取剪切板内容功能，如果剪切板上包含特殊字符[吾家智锁]和[#tempKey]，则密钥页面直接展示数据
        ClipboardManager clipboardManager=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        if(clipboardManager!=null) {
            ClipData cd2 = clipboardManager.getPrimaryClip();
            if (cd2 != null && cd2.getItemCount() > 0) {
                String str2 = cd2.getItemAt(0).getText().toString();
                System.out.println("剪切板内容: " + str2);
                //group 0:all,1:name,2:tempNum,3:tempKey
                String regex = "(?<=门锁)(.*?)的一个临时密钥(.*?)，.*?=(.*?)#";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(str2);
                if(matcher.find() && matcher.groupCount() == 3){
                    tempKeyId = Long.parseLong(matcher.group(3));
                    new Thread(){
                        @Override
                        public void run(){
                            //发送请求获取临时密钥详细信息
                            LockTempKeyApi service = NetComponent.getRetrofit().create(LockTempKeyApi.class);
                            Call<ApiNormalResponse<TempKeyDetail>> call = service.tempKeyDetail(tempKeyId);
                            System.out.println("tempKeyId2: "+tempKeyId);
                            try {
                                ApiNormalResponse<TempKeyDetail> resp = call.execute().body();
                                System.out.println("临时密钥详情： "+resp);
                                // 判断锁是否绑定成功
                                Message msg = handler.obtainMessage();
                                msg.obj = resp;
                                msg.what = 2;
                                handler.sendMessage(msg);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }.start();
                }
            }
        }
    }
}
